package com.blog.blog.service;

import com.blog.blog.mapper.ArticleMapper;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@Service
public class ViewCountService {

	private final ArticleMapper articleMapper;
	private final ConcurrentHashMap<Long, AtomicLong> viewDeltaMap = new ConcurrentHashMap<>();

	public ViewCountService(ArticleMapper articleMapper) {
		this.articleMapper = articleMapper;
	}

	public void incrementView(Long articleId) {
		if (articleId == null) return;
		viewDeltaMap.computeIfAbsent(articleId, k -> new AtomicLong()).incrementAndGet();
	}

	public void flushToDatabase() {
		for (Map.Entry<Long, AtomicLong> e : viewDeltaMap.entrySet()) {
			Long id = e.getKey();
			AtomicLong counter = e.getValue();
			long delta = counter.getAndSet(0);
			if (delta > 0) {
				int inc = (delta > Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) delta;
				articleMapper.increaseViewCountBy(id, inc);
			}
		}
	}
}


